#include "../head.h"

// 无名信号量作用于线程之间
sem_t sem;
int g_val = 0;
void *thread_func1(void *arg)
{
    sem_wait(&sem);
    g_val = 100;
    sleep(2);
    printf("g_val = %d\n", g_val);
    sem_post(&sem);
}

void *thread_func2(void *arg)
{
    sleep(1);
    sem_wait(&sem);
    g_val = 200;
    printf("g_val = %d\n", g_val);
    sem_post(&sem);
}

int main()
{
    printf("main\n");

    // 初始化无名信号量
    // int sem_init(sem_t *sem, int pshared, unsigned int value);
    //  sem无名信号量变量的地址 pshared 0表示进程内信号量 1表示进程间信号量（需要用到共享内存） value 无名信号量的初始值
    sem_init(&sem, 0, 1);

    pthread_t thread1;
    pthread_t thread2;
    pthread_create(&thread1, NULL, thread_func1, NULL);
    pthread_create(&thread2, NULL, thread_func2, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    // 销毁无名信号量
    sem_destroy(&sem);
    return 0;
}